package ind.nuts.lang.validate;


import ind.nuts.lang.utils.EnumUtils;
import ind.nuts.lang.enums.IEnum;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author haoyun.zheng
 */
public class EnumConstraintValidator implements ConstraintValidator<Enum, Integer> {

    private boolean isRequired;
    private Class<? extends IEnum> clazz;

    @Override
    public void initialize(Enum constraintAnnotation) {
        this.isRequired = constraintAnnotation.required();
        this.clazz = constraintAnnotation.type();
    }

    @Override
    public boolean isValid(Integer integer, ConstraintValidatorContext constraintValidatorContext) {
        if (this.isRequired) {
            return integer != null && EnumUtils.contains(this.clazz, integer);
        } else {
            return integer == null || EnumUtils.contains(this.clazz, integer);
        }
    }

}